<?php

namespace Apps\Common\Models;

use Apps\Common\Models\UserBase;
use Apps\Common\Libs\PicUrl;
/**
 * 活动浏览记录Model
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class ActivityViewsUser extends \PhalconPlus\Database\Model
{

    /**
     *
     * @var integer
     */
    public $id;
    public $activity_id;
    public $user_id;
    public $add_time;


    public function getSource()
    {
        return 'activity_views_user';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return Activity[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return Activity
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * Independent Column Mapping.
     * Keys are the real names in the table and the values their names in the application
     *
     * @return array
     */
    public function columnMap()
    {
        return array(
            'id' => 'id',
            'activity_id' => 'activity_id',
            'user_id' => 'user_id',
            'add_time' => 'add_time',
        );
    }

    public function defaultColumns()
    {
        return [
            'add_time',
        ];
    }

    /**
     * 新增浏览用户
     * @param int $activity_id 活动id
     * @param int $user_id 用户id
     */
    public function addData($activity_id, $user_id)
    {
        $this->activity_id = $activity_id;
        $this->user_id = $user_id;
        $this->add_time = date('Y-m-d H:i:s');
        $this->save();
    }

    /**
     * 获取浏览记录的用户列表
     * @param int $activity_id 活动id
     * @param int $offset 分页偏移量
     * @param int $limit 页大小
     * @return array
     */
    public function getViewsUserList($activity_id, $offset = 0, $limit = 10)
    {
        $list = $this->query()->columns([
            'u.user_id',
            'u.user_cover'
        ])->where('activity_id = ' . $activity_id)->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\ActivityViewsUser.user_id', 'u')->groupBy('\Apps\Common\Models\ActivityViewsUser.user_id')->orderBy('add_time DESC')->limit($limit, $offset)->execute()->toArray();

        $result = [];
        foreach ($list as $k => $val) {
            if ($val['user_id']) {
                $val['user_cover'] = PicUrl::UserCover($val['user_cover'], $this->getDi());
                $result[] = $val;
            }
        }

        return $result;
    }

}
